<?php
/**
 * Flea Site
 *
 * @copyright  Copyright (c) 2008 Movoin Studio (http://movoin.com)
 * @license    Apache License 2.0
 * @version    $Id: Products.php 138 2009-05-25 06:42:38Z movoin $
 */

class Model_Products
{
    /**
     * 内容表实例
     *
     */
    var $tblContents;
    /**
     * 分类表实例
     *
     */
    var $tblCategory;

    /**
     * 构造函数
     *
     */
    function Model_Products()
    {
        $this->tblContents = & FLEA::getSingleton( 'Table_Contents' );
        $this->tblCategory = & FLEA::getSingleton( 'Table_Categories' );
    }

    /**
     * 获取指定产品ID的产品信息
     *
     * @parem int $pro_id
     * @parem string $fields
     * @parem string $links
     *
     * @return array
     */
    function getContent($pro_id, $fields='*', $links=null)
    {
        //处理关联表
        if($links) {
            $this->tblContents->enableLinks($links);
        } else {
            $this->tblContents->disableLinks();
        }
        return $this->tblContents->find($pro_id, 'sort_id ASC, id DESC', $fields );
    }

    /**
     * 获取指定分类ID的产品列表
     *
     * @parem string $colkey
     * @parem int $cate_id
     * @parem string $fields
     * @parem string $links
     *
     * @return array
     */
    function getContents($colkey, $cate_id=null, $limit=null, $fields='*', $links=null)
    {
        //处理关联表
        if($links) {
            $this->tblContents->enableLinks($links);
        } else {
            $this->tblContents->disableLinks();
        }
        $where = array(
            array('col_key', $colkey)
        );
        if($cate_id)
            $where[] = array('cate_id', (int)$cate_id);

        return $this->tblContents->findAll($where, 'sort_id ASC, id DESC', $limit, $fields );
    }

    /**
     * 保存产品数据
     *
     * @parem array $data
     * @parem string $file
     *
     * @return string
     */
    function saveProduct(&$data, $file)
    {
        // 开启附件表关联
        $this->tblContents->enableLinks('attachments');
        /**
         * 上传图片
         *
         */
        FLEA::loadFile( 'helper_uploader' );
        $uploader = new helper_uploader(FLEA::getAppInf( 'uploadPath' ), '.jpg/.gif/.png', true, 168, 109);

        if($uploader->isLoaded($file)) {

            $files = $uploader->upload($file);

            foreach($files as $key=>$value) {
                $data['attachments'][] = array(
                        'type' => 'image',
                        'name' => $key,
                        'filename' => $value,
                        'filepath' => FLEA::getAppInf( 'uploadDir' ) . $value
                    );
            }

            //删除原图文件
            if($data['id']) {
                $_row = $this->tblContents->find((int)$data['id']);
                $this->removeAttachments($_row['attachments']);
            }
        }
        /**
         * 保存资料
         *
         */
        $data['col_key'] = $data['colkey'];
        unset($data['colkey']);
        if($this->tblContents->save($data)) {
            return '保存成功!';
        } else {
            return '保存失败!';
        }
    }

    /**
     * 保存产品排序结果
     *
     * @param array $data
     *
     * @return string
     */
    function sortProducts(&$data)
    {
        $data = explode(',', $data);
        foreach($data as $d) {
            $item = explode(':', $d);
            $rows[] = array('id' => $item[0], 'sort_id' => $item[1]);
        }
        if($this->tblContents->updateRowset($rows)) {
            return '保存成功!';
        }
        return '保存失败!';
    }

    /**
     * 删除产品信息
     *
     * @parem int $pro_id
     *
     * @return string
     */
    function removeProduct($pro_id)
    {
        $this->tblContents->enableLinks('attachments');
        $row = $this->tblContents->find($pro_id);
        if($this->tblContents->removeByPkv($pro_id)) {
            // 删除文件
            $this->removeAttachments($row['attachments']);
            return '删除成功!';
        } else {
            return '删除失败!';
        }
    }

    /**
     * 获取指定分类ID的分类信息
     *
     * @parem int $cate_id
     * @parem string $fields
     * @parem string $links
     *
     * @return array
     */
    function getCategory($cate_id, $fields='*', $links=null)
    {
        //处理关联表
        if($links) {
            $this->tblCategory->enableLinks($links);
        } else {
            $this->tblCategory->disableLinks();
        }
        return $this->tblCategory->find($cate_id, 'sort_id ASC, cate_id ASC', $fields );
    }

    /**
     * 获取指定栏目或父类ID的分类信息
     *
     * @parem string $colkey
     * @parem int $parent_id
     * @parem string $fields
     * @parem string $links
     *
     * @return array
     */
    function getCategories($colkey, $parent_id, $fields='*', $links=null)
    {
        //处理关联表
        if($links) {
            $this->tblCategory->enableLinks($links);
        } else {
            $this->tblCategory->disableLinks();
        }
        $where[] = array('col_key', $colkey);
        if(!is_null($parent_id)) {
            $where[] = array('parent_id', (int)$parent_id);
        }
        return $this->tblCategory->findAll($where, 'sort_id ASC, cate_id ASC', null, $fields);
    }

    /**
     * 保存分类排序结果
     *
     * @param array $data
     *
     * @return string
     */
    function sortCategories(&$data)
    {
        $data = explode(',', $data);
        foreach($data as $d) {
            $item = explode(':', $d);
            $rows[] = array('cate_id' => $item[0], 'sort_id' => $item[1]);
        }
        if($this->tblCategory->updateRowset($rows)) {
            return '保存成功!';
        }
        return '保存失败!';
    }

    /**
     * 保存分类数据
     *
     * @parem array $data
     * @parem string $file
     *
     * @return string
     */
    function saveCategory(&$data, $file)
    {
        // 开启附件表关联
        $this->tblCategory->enableLinks('attachments');
        /**
         * 限定分类级数(2级)
         * 当前分类含有子类时，不允许修改其父类
         *
         */
        if($data['cate_id']) {
            $_cate = $this->tblCategory->find(array(array('parent_id', (int)$data['cate_id'])));
            if($_cate) {
                return '当前分类含有子类，无法修改其所属分类!';
            }
            //处于编辑状态时，预读取分类数据，以便删除原图文件
            $_row = $this->tblCategory->find((int)$data['cate_id']);
        }
        /**
         * 上传图片
         *
         */
        FLEA::loadFile( 'helper_uploader' );
        $uploader = new helper_uploader(FLEA::getAppInf( 'uploadPath' ), '.jpg/.gif/.png', true, 168, 109);

        if($uploader->isLoaded($file)) {

            $files = $uploader->upload($file);

            foreach($files as $key=>$value) {
                $data['attachments'][] = array(
                        'type' => 'image',
                        'name' => $key,
                        'filename' => $value,
                        'filepath' => FLEA::getAppInf( 'uploadDir' ) . $value
                    );
            }

            //删除原图文件
            if($_row)
                $this->removeAttachments($_row['attachments']);
        }
        /**
         * 保存资料
         *
         */
        $data['col_key'] = $data['colkey'];
        unset($data['colkey']);
        if($this->tblCategory->save($data)) {
            return '保存成功!';
        } else {
            return '保存失败!';
        }
    }

    /**
     * 删除分类信息
     *
     * @parem int $cate_id
     *
     * @return string
     */
    function removeCategory($cate_id)
    {
        if($this->tblContents->find(array(array('cate_id', $cate_id)))) {
            return '该分类中含有产品，无法删除！';
        }
        $this->tblCategory->enableLinks('attachments');
        $row = $this->tblCategory->find($cate_id);
        if($this->tblCategory->removeByPkv($cate_id)) {
            // 删除文件
            $this->removeAttachments($row['attachments']);
            return '删除成功!';
        } else {
            return '删除失败!';
        }
    }

    /**
     * 删除分类附件(图片)及附件表中的数据记录
     *
     * @parem array $attach
     */
    function removeAttachments($attach)
    {
        $uploadDir = FLEA::getAppInf( 'uploadPath' );

        if($attach) {
            foreach($attach as $att) {
                //获取记录ID
                $atts[] = $att['attach_id'];
                //删除文件
                if(file_exists($uploadDir . DS . $att['filename'])) {
                    unlink($uploadDir . DS . $att['filename']);
                }
            }
            //删除记录
            $tblAttachments =& FLEA::getSingleton( 'Table_Attachments' );
            $tblAttachments->removeByPkvs($atts);
        }
    }

    /**
     * 返回表实例
     *
     */
    function &getTable($type='pro')
    {
        if($type=='pro') {
            return $this->tblContents;
        }
        return $this->tblCategory;
    }

}
